package org.flow.basic.doubts.tjbase.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xl-9527
 * @since 2024/8/30
 */
public class NioMMapJavaIo implements JavaIo {
    @Override
    public void readFile(final String filePath, final int size) {
        try (
                final FileInputStream fileInputStream = new FileInputStream(filePath);
                final RandomAccessFile fileOutputStream = new RandomAccessFile(filePath + "mmap-nio" + System.currentTimeMillis(), "rw")
        ) {
            final FileChannel inChannel = fileInputStream.getChannel();
            final FileChannel outChannel = fileOutputStream.getChannel();
            final int available = fileInputStream.available();
            final long maxSize = 1L << 25;
            if (available > maxSize) {
                int position = 0;
                while (position < available) {
                    final MappedByteBuffer inMap = inChannel.map(FileChannel.MapMode.READ_ONLY, position, Math.min(maxSize, available - position));
                    position += maxSize;
                    if (outChannel.write(inMap) == 0) {
                        break;
                    }
                }
            } else {
                final MappedByteBuffer inMap = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, available);
                outChannel.write(inMap);
                inMap.force();
                inMap.clear();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void writeFile(final byte[] bytes, final FileOutputStream fileOutputStream) throws IOException {
    }
}
